package com.century.sjt.activity.Pay;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.activity.MyOrderDetailsActivity;
import com.century.sjt.adapter.CommodityAdapter;
import com.century.sjt.entity.Commodit;
import com.century.sjt.entity.Merchant;
import com.century.sjt.entity.MyOrderInfo;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.waterfall.dodowaterfall.Helper;
import com.century.sjt.waterfall.imageloader.ImageLoader;
import com.century.sjt.waterfall.lib.internal.PLA_AdapterView;
import com.century.sjt.waterfall.util.ImageFetcher;
import com.century.sjt.waterfall.view.XListView;
import com.century.sjt.waterfall.view.XListView.IXListViewListener;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommodityListActivity extends BaseActivity implements IXListViewListener {
    private XListView mAdapterView;
    private CommodityAdapter mAdapter;
    private int currentPage = 1;
    private SjtTitleBar titleBar;
    private ImageLoader mLoader;
    private Handler mHandler;
    private Button btnOrder;//下单
    private LinearLayout layout_Order;
    private Boolean isDataChangeOk = true;        //是否加载成功
    private List<Commodit> result = new ArrayList<>();
    private List<Commodit> selectList=new ArrayList<>();
    private String shopId;//分店id
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_pull_to_refresh_sample);

        Intent intent = getIntent();
        shopId = intent.getStringExtra("shopId");
        //获得从activity中传递过来的值
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mAdapter.notifyDataSetChanged();
                        break;
                    case 2:
                        isDataChangeOk = true;
                        result.clear();
                        currentPage = 1;
                        getCommodit(1);
                        break;
                    case 3:
                        if (isDataChangeOk) {
                            currentPage ++;
                            getCommodit(2);
                        }
                        break;

                }
            }
        };


        DisplayMetrics dm = new DisplayMetrics();
        int screenWidth = dm.widthPixels;//屏幕宽
        WindowManager wm1 = this.getWindowManager();
        int width1 = wm1.getDefaultDisplay().getWidth();
        mLoader = new ImageLoader(CommodityListActivity.this);
        mLoader.setIsUseMediaStoreThumbnails(false);
        mLoader.setRequiredSize(width1);
//		requiredSize = screenWidth;
//        Log.e("ll", width1 + "");

        initView();
        initEvent();
        initData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        AddItemToContainer(currentPage, 2);
        Message msg = new Message();
        msg.what = 2;
        mHandler.sendMessage(msg);
//        getCommodit(currentPage, 1);
    }

    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.tab_commodit));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnOrder = (Button) findViewById(R.id.btn_place_an_order);
        layout_Order = (LinearLayout) findViewById(R.id.layout_btn_place_an_order);
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String isMerchant = mainSharedPreferences.getString("isMerchant", "");
        String isShop = mainSharedPreferences.getString("isShop", "");
//        Log.d("Tag","是否是商家："+isMerchant+"是否是分店："+isShop);
        //判断是商家、分店还是用户
        if (isMerchant.equals("0")&isShop.equals("0")){
            layout_Order.setVisibility(View.VISIBLE);
        }else{
            layout_Order.setVisibility(View.GONE);
        }
        mAdapterView = (XListView) findViewById(R.id.list);
        mAdapterView.setPullLoadEnable(true);
        mAdapterView.setXListViewListener(this);
        mAdapter = new CommodityAdapter(this, mAdapterView, mHandler, mLoader,result);
        mAdapterView.setAdapter(mAdapter);

        mAdapterView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(CommodityListActivity.this, CommodityActivity.class);
                intent.putExtra("url", result.get(position-1).getDetailsUrl());
                intent.putExtra("shopId",shopId);
                intent.putExtra("goodId",result.get(position).getGoodId());
                intent.putExtra("shareUrl",result.get(position).getShareUrl());
                intent.putExtra("goodName",result.get(position).getGoodName());
                intent.putExtra("mainImageUrl",result.get(position).getMainImageUrl());
                startActivity(intent);
            }
        });

    }

    @Override
    protected void initEvent() {
        //orderIdList = new ArrayList<>();
        //下单
        btnOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String goodId=null;
                for(int i = 0; i <result.size(); i++){
                    if (result.get(i).isSelect()){
                        selectList.add(result.get(i));
                    }
                }
                for(int j=0;j<selectList.size();j++){
                    if (j>0){
                        goodId+="|"+selectList.get(j).getGoodId();
                    }else{
                        goodId=selectList.get(j).getGoodId();
                    }
                }
                placeAnOrder(goodId);
            }
        });


    }

    private interface OrderClickListener {
        void onSuccess(MyOrderInfo orderInfo);
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onRefresh() {
//        AddItemToContainer(currentPage=0, 1);
        Message msg = new Message();
        msg.what = 2;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onLoadMore() {
//        AddItemToContainer(++currentPage, 2);
        if (isDataChangeOk) {
            Message msg = new Message();
            msg.what = 3;
            mHandler.sendMessage(msg);
        } else {
            mAdapterView.stopLoadMore();
            mAdapter.notifyDataSetChanged();
        }

    }

    /**
     * 获取商品列表
     *
     * @param
     */
    private void getCommodit( final int type) {

        isDataChangeOk = false;        //是否更新成功
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), CommodityListActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ShopGoods, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
//
                    if (code.equals("200")) {//成功
                        isDataChangeOk = true;
                        JSONObject data = res.getJSONObject("data");
                        shopId = data.getString("shopId");
                        String shopUserId = data.getString("shopUserId");
                        JSONArray goodList = data.getJSONArray("goodList");
                        if (goodList.length() != Constant.PAGESIZE) {
                            isDataChangeOk = false;
                        }
                        for (int i = 0; i < goodList.length(); i++) {
                            JSONObject good = (JSONObject) goodList.get(i);
                            Commodit commodit = new Commodit();
                            commodit.setPrice(good.getString("price"));
                            commodit.setOriginalPrice(good.getString("originalPrice"));
                            commodit.setDescription(good.getString("description"));
                            commodit.setDetailsUrl(good.getString("detailsUrl"));
                            commodit.setMainImageUrl(good.getString("mainImageUrl"));
                            commodit.setGoodName(good.getString("goodName"));
                            commodit.setCurrency(good.getString("currency"));
                            commodit.setSelect(false);
                            commodit.setGoodId(good.getString("goodId"));
                            commodit.setShareUrl(good.getString("shareUrl"));
                            result.add(commodit);
                        }

                    } else {//失败
                        isDataChangeOk = false;

                        currentPage--;
                        if (type == 1) {
                            mAdapterView.stopRefresh();
                        } else if (type == 2) {
                            mAdapterView.stopLoadMore();
                        }
                        Toast.makeText(CommodityListActivity.this, "没有更商品", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    Toast.makeText(CommodityListActivity.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }
                if (type == 1) {
                    mAdapter.notifyDataSetChanged();
                    mAdapterView.stopRefresh();
                } else if (type == 2) {
                    mAdapterView.stopLoadMore();
                    mAdapter.notifyDataSetChanged();
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (type == 1) {
                    mAdapterView.stopRefresh();
                } else if (type == 2) {
                    mAdapterView.stopLoadMore();
                }
                currentPage --;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.showToast(getResources().getString(R.string.error_network), CommodityListActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId", shopId);
                map.put("paging.currentPage", currentPage + "");
                map.put("paging.pageSize", Constant.PAGESIZE + "");
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    /**
     * @Description: 创建订单
     * @author: 周玲波
     * @date: 2016/8/29 17:19
     */
    private void placeAnOrder(final String goodId) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.createMyOrderHost, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        JSONObject data = res.getJSONObject("data");
                        String orderId = data.getString("orderid");
                       // MyOrderInfo orderInfo = new MyOrderInfo();
                       // orderInfo.setOrderId(orderId);
                      //  orderIdList.add(orderInfo);
                        if (!(orderId.equals("null"))){
                        //Gson gson = new Gson();
                       // String id= gson.toJson(orderIdList);
                        Intent intent = new Intent(CommodityListActivity.this, MyOrderDetailsActivity.class);
                        intent.putExtra("orderId", orderId);
                        intent.putExtra("falg",1);
                        startActivity(intent);
                        }else{
                            TipUtil.showToast(getResources().getString(R.string.text_please_choose_goods), CommodityListActivity.this, 1);
                        }
                    } else {
                        TipUtil.showToast(message, CommodityListActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), CommodityListActivity.this, 1);
                }
                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), CommodityListActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("shopId", shopId);//分店id
                map.put("goodId", goodId);//商品id
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

}// end of class
